import random
import string

from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django_redis import get_redis_connection
from django.views.generic import View
from authApp.forms import RegisterForm, LoginForm
from authApp.models import UserInfo


# Create your views here.
class CaptchaManager:
    @staticmethod
    def generate_captcha_data(request):
        """生成验证码数据并更新会话"""
        hashkey = CaptchaStore.generate_key()
        request.session['captcha_hashkey'] = hashkey
        request.session.set_expiry(120)
        return {
            'hashkey': hashkey,
            'image_url': captcha_image_url(hashkey)
        }

    @staticmethod
    def validate_captcha(request, user_input):
        """验证码验证逻辑"""
        hashkey = request.session.get('captcha_hashkey')
        request.session.pop('captcha_hashkey', None)  # 立即清除会话中的验证码信息

        if not hashkey:
            return False, "验证码信息丢失，请刷新重试"

        captcha = CaptchaStore.objects.filter(hashkey=hashkey).first()
        if not captcha:
            return False, "验证码已过期，请刷新重试"

        if user_input.lower() != captcha.response.lower():
            return False, "验证码输入错误"

        captcha.delete()  # 验证通过后删除验证码记录
        return True, ""

def refresh_captcha(request):
    return JsonResponse(CaptchaManager.generate_captcha_data(request))

class LoginView(View):
    def get(self, request):
        captcha = CaptchaManager.generate_captcha_data(request)
        form = LoginForm()
        return render(request, "login.html",
                      {'from': form, 'captcha': captcha})
    def post(self, request):
        form = LoginForm(data=request.POST)

        if form.is_valid():
            user_code = form.cleaned_data['captcha']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            remember = form.cleaned_data['remember']
            is_valid, error_msg = CaptchaManager.validate_captcha(request, user_code)
            if not is_valid:
                form.add_error('captcha', error_msg)
            user = UserInfo.objects.filter(email=email, password=password).first()
            if user:
                request.session['user_email'] = user.email
                request.session.set_expiry(1209600 if remember else 0)
                return redirect('clientApp:index')
            form.add_error('email',"用户名或密码错误")
        return render(request,'login.html',
                      {'form': form, 'captcha': CaptchaManager.generate_captcha_data(request)})



class RegisterView(View):
    def get(self, request):
        return render(request, "register.html",
                      {'form': RegisterForm()})
    def post(self, request):
        form = RegisterForm(request.POST)
        print(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            user = UserInfo.objects.create(
                username=username,
                email=email,
                password=password
            )
            user.save()
            return JsonResponse({'status': True, 'data': '/auth/login/'})
        return JsonResponse({'status': False, 'errors': form.errors})

def send_regCaptcha(request):
    email = request.GET.get('email')
    exists = UserInfo.objects.filter(email=email).exists()
    if exists:
        return JsonResponse({'code': 400, 'message': '该邮箱已被注册！'})
    # 验证邮箱
    if not email:
        return JsonResponse({'code': 400, 'message': '请输入正确的邮箱！'})
    # 生成验证码
    captcha = ''.join(random.sample(string.digits, 6))
    # 发送验证码
    try:
        send_mail("海台数据分析系统注册验证码", message=f"您注册验证码是：{captcha},有效期为5分钟",
                  recipient_list=[email], from_email=None)
    except Exception as e:
        return JsonResponse({'code': 500, 'message': f"邮件发送失败: {str(e)}"})
    # 更新验证码数据库
    conn = get_redis_connection()
    conn.set(email, captcha, ex=300)
    return JsonResponse({'code': 200, 'message': '邮箱验证码发送成功！'})

